package com.mg.plugin.agrometeorology.common;


import com.mg.plugin.agrometeorology.entity.StationData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiaolu
 */
public class AssistStationData {
    public static Map<String,List<StationData>> mapByStationId(Map<String,String> headerIndex, List<String> stationDataList) {
        Map<String,List<StationData>> resultStationData = new HashMap<String, List<StationData>>();
        if (null != stationDataList && stationDataList.size() > 2) {
            String realHeader = stationDataList.get(0);
            executeData(stationDataList, resultStationData, realHeader, headerIndex);
        }
        return resultStationData;
    }

    private static void executeData(List<String> stationDataList, Map<String,List<StationData>> resultStationData, String realHeader, Map<String,String> headerIndex) {
        int stationIdIndex = findDataIndex(realHeader, headerIndex.get("StationId"));
        int dateIndex = findDataIndex(realHeader, headerIndex.get("Date"));
        int tempIndex = findDataIndex(realHeader, headerIndex.get("Temp"));
        int oldTempIndex = findDataIndex(realHeader, headerIndex.get("OldTemp"));

        for (int i = 2; i < stationDataList.size(); i++) {
            String[] data = stationDataList.get(i).split(",");
            String stationId = data[stationIdIndex];
            StationData stationData = new StationData();
            stationData.setStationId(stationId);
            stationData.setDate(data[dateIndex]);
            stationData.setTemp(Float.parseFloat(data[tempIndex]));
            stationData.setOldTemp(Float.parseFloat(data[oldTempIndex]));

            if (resultStationData.keySet().contains(stationId)) {
                resultStationData.get(stationId).add(stationData);
            } else {
                List<StationData> dataList = new ArrayList<StationData>();
                dataList.add(stationData);
                resultStationData.put(stationId, dataList);
            }
        }
    }

    private static int findDataIndex(String realHeader, String strRain) {
        String[] data = realHeader.split(",");
        for (int i = 0; i < data.length; i++) {
            if (data[i].equalsIgnoreCase(strRain)) {
                return i;
            }
        }
        return -1;
    }

}
